"""
    Software : PyCharm
    File     : serializers.py
    Time     : 2021/6/2 21:47
    Author   : Pontoon
    describe :
"""
from rest_framework import serializers
from .models import Group, GroupMessage


class GroupSerializer(serializers.ModelSerializer):
    creator = serializers.SerializerMethodField()
    member = serializers.SerializerMethodField()

    class Meta:
        model = Group
        fields = ["id", "creator", "member", "name", "create_time"]

    def get_creator(self, instance):
        data = {}
        data['uid'] = instance.creator.uid
        data['nickname'] = instance.creator.nickname
        data['avatar'] = instance.creator.avatar
        return data

    def get_member(self, instance):
        user_list = instance.member.all()
        li = []
        if len(user_list) > 0:
            for user in user_list:
                li.append({"uid": user.uid, "nickname": user.nickname, "avatar": user.avatar})
        return li


class GroupMessageSerializer(serializers.ModelSerializer):
    group = serializers.CharField(source="group.id")
    user = serializers.SerializerMethodField()

    class Meta:
        model = GroupMessage
        fields = ["id", "group", "user", "message", "create_time"]

    def get_user(self, instance):
        data = {}
        data['uid'] = instance.creator.uid
        data['nickname'] = instance.creator.nickname
        data['avatar'] = instance.creator.avatar
        return data




